package com.hg.onlineshop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hg.onlineshop.entity.User;
import com.hg.onlineshop.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/save")
    public String saveUser(@RequestBody User user) {
        int flag = userMapper.updateById(user);
        if (flag > 0) {
            return "S";
        }
        return "E";
    }

    @GetMapping("/list/{size}/{current}")
    public Page<User> findPageUsers(@RequestParam(required = false) User user,Page page) {
        Page<User> users = userMapper.selectPage(page, Wrappers.<User>lambdaQuery());
        return users;
    }

    @GetMapping("/single")
    public User getUser(User user) {
        Integer userId = user.getId();
        if (userId == null) {
            return null;
        }
        User returnUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getId, userId));
        return returnUser;
    }

    @PostMapping("/admin/login")
    public User adminLogin(@RequestBody User user, HttpSession session) {
        User queryUser = new User();
        queryUser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()).eq(User::getUserPassword, user.getUserPassword()).eq(User::getDelStatus, "0").ne(User::getUserType, "普通会员"));
        if (queryUser != null) {
            // 用户信息存到session
            session.setAttribute("user", queryUser);
            return queryUser;
        }
        return queryUser;
    }

    @PostMapping("/login")
    public User userLogin(@RequestBody User user, HttpSession session) {
        User returnUser = new User();
        if (user == null) {
            return returnUser;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", user.getUserName()).eq("user_password", user.getUserPassword());
        returnUser = userMapper.selectOne(queryWrapper);
        if (returnUser != null) {
            // 用户信息存到session
            session.setAttribute("user", returnUser);
            return returnUser;
        }
        return returnUser;
    }
}
